package com.xuexi.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 梁二东
 * @Date: 2024/11/16 13:54
 * @Description: 字符串z字变形
 **/
public class ZTransform {

    public static void main(String[] args) {
        // PAYPALISHIRING -> PAHNAPLSIIGYIR

        /*
        P   A   H   N
        A P L S I I G
        Y   I   R
         */
        System.out.println(ztransform("PAYPALISHIRING", 3));
    }

    /**
     * @param s          目标 string
     * @param lineNumber 行数
     * @return
     */
    public static String ztransform(String s, int lineNumber) {
        if (lineNumber < 2 || s.length() <= lineNumber) {
            return s;
        }
        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < lineNumber; i++) {
            rows.add(new StringBuilder());
        }
        //当前所在行
        int curr = 0;
        int flag = -1;
        // curr +- flag 来移动所在行
        for (char c : s.toCharArray()) {
            if (curr == 0 || curr == lineNumber - 1) {
                flag = -flag;
            }
            rows.get(curr).append(c);
            curr += flag;
        }

        StringBuilder result = new StringBuilder();
        for (StringBuilder row : rows) {
            result.append(row);
        }
        return result.toString();
    }
}
